using System;
using System.IO;
using System.Net;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

#if WINDOWS_PHONE
using System.Windows.Resources;
#elif WINDOWS_RT
using System.Net.Http;
using System.Threading.Tasks;
#endif

namespace AdRotatorXNA.Helpers
{
    class ImageDownload
    {
        internal static void GetImageFromURL(GraphicsDevice graphics, string imageUrl, Action<Texture2D, Exception> callback)
        {
            if (string.IsNullOrEmpty(imageUrl))
            {
                callback(null, new Exception());
                return;
            }
            Uri ImageURI = new Uri(imageUrl);

            try
            {
                
#if WINDOWS_RT
                var client = new HttpClient();

                // minimum timeout we can set it to: 
                // http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.timeout.aspx
                client.Timeout = TimeSpan.FromSeconds(15);

                Task.Run(async () =>
                {


                    try
#else
                WebClient client = new WebClient();
                
#if !iOS
                    client.AllowReadStreamBuffering = true;
#endif

                client.OpenReadCompleted += (s, e) =>
                {
                    if (e.Error != null)
                    {
                        var errorimage = new Texture2D(graphics, 1, 1);
                        errorimage.SetData<Color>(new Color[1] { Color.Gray });
                        callback(errorimage, e.Error);
                    }
                    else
#endif
                    {

#if WINDOWS_RT
                        var stream = await client.GetStreamAsync(ImageURI);

                        Texture2D image = null;

                        // For some reason, Texture2D.FromStream has a problem with
                        // a stream fetched from the web.
                        using (var ms = new MemoryStream())
                        {
                            stream.CopyTo(ms);
                            ms.Seek(0, SeekOrigin.Begin);
                            image = Texture2D.FromStream(graphics, ms);
                        }

#elif iOS                      
                        var image = Texture2D.FromStream(graphics, e.Result as Stream);
#else                     
                        StreamResourceInfo sri = new StreamResourceInfo(e.Result as Stream, null);                        
                        var image = Texture2D.FromStream(graphics, sri.Stream);
#endif

                        callback(image, null);
                    }
#if WINDOWS_RT
                    catch (Exception e)
                    {
                        callback(null, e);
                    }
                    });
#else
                    };

                client.OpenReadAsync(ImageURI);
#endif
            }
            catch (Exception e)
            {
                callback(null, e);
            }
        }
    }
}
